//
//  DCTabBar.m
//  

#import "DCTabBar.h"
#import "DCTabBarButton.h"

@interface DCTabBar()

@property (nonatomic, strong) NSMutableArray *tabBarButtons;
@property (nonatomic, weak) DCTabBarButton *selectedButton;

@end


@implementation DCTabBar


/**懒加载*/
- (NSMutableArray *)tabBarButtons{
    if (_tabBarButtons == nil) {
        _tabBarButtons = [NSMutableArray array];
    }
    return _tabBarButtons;
}

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    return self;
}


- (void)addTabBarButtonWithItem:(UITabBarItem *)item{
    //1.创建按钮
    DCTabBarButton *button = [[DCTabBarButton alloc] init];
    button.layer.borderColor = [UIColor blackColor].CGColor;
    button.layer.borderWidth = 1;
    [self addSubview:button];
    
    //2.添加按钮到数组中
    [self.tabBarButtons addObject:button];
    
    //3.设置数据
    button.item = item;
    
    //4.监听按钮点击
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchDown];
    
    //5.默认选中第0个按钮
    if (self.tabBarButtons.count == 1) {
        [self buttonClick:button];
    }
}


- (void)setTabBarIndex:(NSInteger)tabBarIndex{
    _tabBarIndex = tabBarIndex;
    if (tabBarIndex != 0) {
        DCTabBarButton *button = self.tabBarButtons[tabBarIndex];
        [self buttonClick:button];
    }
}


/**监听按钮点击*/
- (void)buttonClick:(DCTabBarButton *)button{
    //1.通知代理
    if ([self.delegate respondsToSelector:@selector(tabBar:didSelectedButtonFrom:to:)]) {
        [self.delegate tabBar:self didSelectedButtonFrom:self.selectedButton.tag to:button.tag];
    }
    
    //2.设置按钮的状态
    self.selectedButton.selected = NO;
    button.selected = YES;
    self.selectedButton = button;
    
    
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    //按钮的frame数据
    CGFloat h = self.frame.size.height;
    CGFloat w = self.frame.size.width;
    
    CGFloat buttonH = h;
    CGFloat buttonW = w / self.subviews.count;
    CGFloat buttonY = 0;
    
    for (int index = 0; index < self.tabBarButtons.count; index++) {
        //1.取出按钮
        DCTabBarButton *button = self.tabBarButtons[index];
        
        //2.设置按钮的frame
        CGFloat buttonX = index * buttonW;
        
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
        
        //3.绑定tag
        button.tag = index;
        
    }
    
    
    
}





@end
